package com.example.sys.org.service.impl;

import com.example.core.convert.context.RequestContext;
import com.example.core.hql.HQLInfo;
import com.example.core.service.XMLDataBean;
import com.example.core.service.impl.BaseServiceImpl;
import com.example.sys.org.dao.SysOrgElementDao;
import com.example.sys.org.model.SysOrgConstant;
import com.example.sys.org.model.SysOrgElement;
import com.example.sys.org.service.SysOrgElementService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysOrgElementServiceImpl extends BaseServiceImpl<SysOrgElementDao, SysOrgElement> implements SysOrgElementService, XMLDataBean {

    @Override
    public List<SysOrgElement> getData(RequestContext requestContext) throws Exception {
        List<SysOrgElement> data = new ArrayList<>();
        List<SysOrgElement> sysOrgElements = this.getRoot(requestContext);
        for (SysOrgElement sysOrgElement : sysOrgElements) {
            data.add(buildNode(requestContext, sysOrgElement));
        }
        return data;
    }

    @Override
    public List<SysOrgElement> getNodeByPId(RequestContext requestContext, String parentId) throws Exception {
        HQLInfo info = new HQLInfo();
        info.setWhereBlock("sysOrgElement.fdParent.fdId =:parentId and sysOrgElement.fdOrgType =:fdOrgType");
        info.setParameter("fdOrgType", SysOrgConstant.ORG);
        info.setParameter("parentId", parentId);
        return findList(info);
    }

    @Override
    public List<SysOrgElement> getRoot(RequestContext requestContext) throws Exception {
        HQLInfo info = new HQLInfo();
        info.setWhereBlock(" sysOrgElement.fdParent is null and sysOrgElement.fdOrgType =:fdOrgType");
        info.setParameter("fdOrgType", SysOrgConstant.ORG);
        return findList(info);
    }

    @Override
    public SysOrgElement buildNode(RequestContext requestContext, SysOrgElement root) throws Exception {
        List<SysOrgElement> chlidList = this.getNodeByPId(requestContext, root.getFdId());
        root.setChildren(chlidList);
        if (!chlidList.isEmpty()) {
            for (SysOrgElement sysOrgElement : chlidList) {
                buildNode(requestContext, sysOrgElement);
            }
        }
        return root;
    }

}
